package com.suieqian.util;

import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件操作
 *
 * @author lirch
 */
public class FileUtil {
    /**
     * 文件下载
     *
     * @param path
     * @param response
     * @throws IOException
     */
    public static void downloadFile(String path, HttpServletResponse response) throws IOException {
        File file = new File(path);
        String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());
//        // 后缀
//        String ext = fileName.substring(fileName.lastIndexOf("."));
        // 以流的形式下载文件
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        os.write(buffer);
        os.flush();
        os.close();
    }

    public static void downloadFile(byte[] buffer, String name, String ext, HttpServletResponse response) throws IOException {
//        File file = new File(path);
//        String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());
//        // 后缀
//        String ext = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
        // 以流的形式下载文件
        ByteArrayInputStream in = new ByteArrayInputStream(buffer);
        InputStream fis = new BufferedInputStream(in);
        fis.close();
        in.close();

        response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("utf-8"), "ISO-8859-1") + ext);
        response.addHeader("Content-Length", "" + buffer.length);
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        os.write(buffer);
        os.flush();
        os.close();
    }

    /**
     * 删除文件
     *
     * @param path
     * @return
     */
    public static boolean delete(String path) {
        if (StrUtil.isBlank(path)) {
            return false;
        }
        File file = new File(path);
        return file.delete();
    }
}
